#include<iostream>
#include<vector>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<string>
typedef long long ll;
using namespace std;
vector<int>g[11];
int v[11];
ll ans,sum;
void dfs(int d,int pre,int val,int x,int f)
{
    if(d==6)
    {
        ans=min(ans,sum-val+x);
        return ;
    }
    for(int i=0;i<=9;i++)
    {
        if(!g[i].size()) continue;
        if(i==0)
        {
            if(f)
            {
                dfs(d+1,-1,val+v[i],10*x+i,f?i==0:0);
                continue;
            }
        }
        int now=upper_bound(g[i].begin(),g[i].end(),pre)-g[i].begin();
        if(now>=g[i].size()) continue;
        dfs(d+1,g[i][now],val+v[i],10*x+i,f?i==0:0);
    }
}
void solve()
{
    string s;
    int c,t;
    cin>>c>>t;
    while(t--)
    {
        for(int i=1;i<=9;i++) g[i].clear();
        g[0].push_back(0);
        cin>>s;
        for(int i=1;i<=9;i++) cin>>v[i];
        sum=0;
        for(int i=0;i<s.size();i++)
        {
            sum+=v[s[i]-'0'];
            g[s[i]-'0'].push_back(i);
        }
        ans=sum;
        dfs(1,-1,0,0,1);
        cout<<ans<<endl;
    }
}
int main()
{
    ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
    // freopen("PXXXX.in","r",stdin);
    // freopen("PXXXX.out","w",stdout);
    solve();
    return 0;
}